<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace SDXApi\Model;
use Think\Model;
use Think\Template\Driver\Mobile;

class UseraddressModel extends Model
{
    protected $tableName = 'user_address';
    
    /*
     * 获取我的收货地址
     * */
    public function get_address_list($uid,$page){
        $where=array('user_id'=>$uid);
        $count=$this->get_addresscount($where);
        $pagearr=show_page($count,$page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        //查询是否为196用户
        $is_891 = M('users')->where(array('user_id' => $uid))->getField('is_891');

        $res=$this->field('address_tag,sex,address_id,address_name,consignee,country,province,city,district,address,zipcode,mobile,best_time,default,sign_building')
             ->where($where)
             ->limit($pagearr['firstpage'].','.C('page_size'))
             ->order('address_id desc')
             ->select();

//        dd($res);
        if($res){
            foreach ($res as $k=>$v){
                $country_name=M('region')->where('region_id ='.$v['country'])->getField('region_name');
                $province_name=M('region')->where('region_id ='.$v['province'])->getField('region_name');
                $city_name=M('region')->where('region_id ='.$v['city'])->getField('region_name');
                $district_name=M('region')->where('region_id ='.$v['district'])->getField('region_name');
                $res[$k]['id']=$v['address_id'];
                $res[$k]['country_name']=$country_name;
                $res[$k]['province_name']=$province_name;
                $res[$k]['city_name']=$city_name;
                $res[$k]['district_name']=$district_name;
                $res[$k]['is_default']=$v['default'];
                //获取显示出配送区域与送货到达时间
                $res[$k]['fac'] = $this->check_serve_by_address_id($v['address_id']);

                //196用户：仓库id用主仓对应的虚拟仓
                if($is_891 == 2){
                    $res[$k]['fac']['wid'] = M('warehouse')->where(array('pid' => $res[$k]['fac']['wid']))->getField('id');
                }


                $res[$k]['fac']['price'] = A("Statement")->calc_freight(0,0,true);

                $res[$k]['dis_time']=D("Users")->distributie_time_list_new($res[$k]['fac']['mode_id'], $res[$k]['fac']['wdr_id']);
                //$res[$k]['dis_time']=A("Order")->get_distribution_time($v['address_id']);

//                安卓地址不能为空
                if(empty($v['address'])){
                    $res[$k]['address'] = $v['sign_building'];
                }

            }
            $data=array('list'=>$res,'is_bottom'=>$is_last,'page'=>$pagearr);
            return $data;
        }else{
            return false;
        }
    }
    
    /*
     * 新增收货地址
     * */
    public function add_address($adddata=array()){
        if(count($adddata)>0){
            $data=array(
                'address_name'=>$adddata['address_name'],
                'user_id'=>$adddata['user_id'],
                'consignee'=>$adddata['consignee'],
//                 'email'=>$adddata['email'],
                'country'=>$adddata['country'],
                'province'=>$adddata['province'],
                'city'=>$adddata['city'],
                'district'=>$adddata['district'],
                'address'=>$adddata['address'],
//                	'tel'=>$adddata['tel'],
//                 'zipcode'=>$adddata['zipcode'],
                'mobile'=>$adddata['mobile'],
                'address_tag'=>$adddata['address_tag'],
                'sex'=>$adddata['sex'],
                'sign_building'=>$adddata['sign_building'],
//                 'best_time'=>$adddata['best_time'],
                'default'=>0,
                'longitude'=>$adddata['longitude'],
                'latitude'=>$adddata['latitude']
            );
            $id=$this->add($data);
            if($id){
                $_SESSION ['direct_shopping'] = 1;
                return $id;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
 /*
     * 修改收货地址
     * */
    public function edit_address($adddata=array()){
        if(count($adddata)>0){
            $data=array(
                'address_name'=>$adddata['address_name'],
                'consignee'=>$adddata['consignee'],
                'email'=>$adddata['email'],
                'country'=>$adddata['country'],
                'province'=>$adddata['province'],
                'city'=>$adddata['city'],
                'district'=>$adddata['district'],
                'address'=>$adddata['address'],
                'tel'=>$adddata['tel'],
                'zipcode'=>$adddata['zipcode'],
                'mobile'=>$adddata['mobile'],
                'sign_building'=>$adddata['sign_building'],
                'best_time'=>$adddata['best_time'],
                'default'=>$adddata['default'],
                'longitude'=>$adddata['longitude'],
                'latitude'=>$adddata['latitude']
            );
            $id=$this->where(array('user_id'=>$adddata['user_id'],'address_id'=>$adddata['address_id']))->save($data);
            if($id!==false){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    /*
     * 收货地址详情
     * */
    
    public function get_address_details($adddata=array()){
    		$where=array('address_id'=>$adddata['address_id'],'user_id'=>$adddata['user_id']);
            $res=$this->field('sex,address_tag,address_id,address_name,consignee,country,province,city,district,address,zipcode,mobile,best_time,default')
                      ->where($where)
                      ->find();
            if($res){
            	//获取显示出配送区域与送货到达时间
            	$res['is_default'] = $res['default'];
            	$res['fac']=$this->check_serve_by_address_id($adddata['address_id']);
                $res['dis_time']=A("Order")->get_distribution_time($adddata['address_id']);

                $res['fac']['price'] = A("Statement")->calc_freight(0,0,true);


                //查询是否为196用户
                $is_891 = M('users')->where(array('user_id' => $adddata['user_id']))->getField('is_891');
                //196用户：仓库id用主仓对应的虚拟仓
                if($is_891 == 2){
                    $res['fac']['wid'] = M('warehouse')->where(array('pid' => $res['fac']['wid']))->getField('id');
                }


                return $res;
            }else{
                return false;
            }
    }
    
    /*
     * 设定我的默认地址
     * */
    public function set_address_dafult($uid,$address_id){
        $where=array('address_id'=>$address_id,'user_id'=>$uid);
        $this->where(array('user_id'=>$uid,'default'=>1))->save(array('default'=>0));
        $id=$this->where($where)->save(array('default'=>1));
        if($id!==false){
            $_SESSION ['direct_shopping'] = 1;
            return true;
        }else{
            return false;
        }
    }
    
    /*
     * 获取我的默认地址
     * 
     * */
    public function get_address_dafult($uid,$address_id=0){
    	if($address_id){
    		$where=array('user_id'=>$uid,'address_id'=>$address_id);
    	}else{
    		$where=array('user_id'=>$uid,'default'=>1);
    	}
        
        $res=$this->field('address_id,user_id,sex,address_tag,address_name,consignee,country,province,city,district,address,zipcode,mobile,best_time,default,sign_building')
        ->where($where)
        ->find();
        if($res){
            if(empty($res['sign_building'])||empty($res['address'])){
                returnApiError("地址地标为空，请修改后再结算");
            }else{
                $res['is_default'] = $res['default'];
                $res['fac']=$this->check_serve_by_address_id($res['address_id']);
                $res['dis_time']=A("Order")->get_distribution_time($res['address_id']);

                //查询是否为196用户
                $is_891 = M('users')->where(array('user_id' => $res['user_id']))->getField('is_891');
                //196用户：仓库id用主仓对应的虚拟仓
                if($is_891 == 2){
                    $res['fac']['wid'] = M('warehouse')->where(array('pid' => $res['fac']['wid']))->getField('id');
                }

                $_SESSION ['direct_shopping'] = 1;
                return $res;
            }

        }else{
            return  false;
        }
    }
    
    /*
     * 删除我的收货地址
     * */
    public function del_address($uid,$address_id){
        $where=array('user_id'=>$uid,'address_id'=>$address_id);
        $is_default = $this->where($where)->getField('default');
        $id=$this->where($where)->delete();
        if($id!==false){
        	//如果删除的地址是收货地址，则取存在的一个地址自动设为默认地址
        	if($is_default){
        		$map = array('user_id'=>$uid);
        		$address = $this->where($map)->find();
        		//如果存在地址，设为默认地址
        		if(!empty($address)){
        			$map['address_id'] = $address['address_id'];
        			$this->where($map)->setField('default',1);
        		}
        	}
            return true;
        }else{
            return false;
        }
    }
    
    
    /**
     * 检查收货人信息是否完整
     * @param   array   $consignee  收货人信息
     * @param   int     $flow_type  购物流程类型
     * @return  bool    true 完整 false 不完整
     */
    public function check_consignee_info($consignee, $flow_type) {
        if ($this->exist_real_goods(0, $flow_type)) {
            /* 如果存在实体商品 */
            $res = !empty($consignee['consignee']) &&
            !empty($consignee['country']) &&
            !empty($consignee['mobile']) &&
                !empty($consignee['address']) &&
                !empty($consignee['sign_building']);
    
            if ($res) {
                if (empty($consignee['province'])) {
                    /* 没有设置省份，检查当前国家下面有没有设置省份 */
                    $pro = D('Region')->get_regions($consignee['country'],1);
                    $res = empty($pro['regionlist']);
                } elseif (empty($consignee['city'])) {
                    /* 没有设置城市，检查当前省下面有没有城市 */
                    $city = D('Region')->get_regions($consignee['province'],2);
                    $res = empty($city['regionlist']);
                } elseif (empty($consignee['district'])) {
                    $dist = D('Region')->get_regions($consignee['city'],3);
                    $res = empty($dist['regionlist']);
                }elseif(empty($consignee['address'])){
                	$res = empty($consignee['address']);
                }elseif(empty($consignee['address'])){
                    $res = empty($consignee['address']);
                }
            }
    
            return $res;
        } else {
            /* 如果不存在实体商品 */
            return !empty($consignee['consignee']);
        }
    }
    
    
    /**
     * 查询购物车（订单id为0）或订单中是否有实体商品
     * @param   int     $order_id   订单id
     * @param   int     $flow_type  购物流程类型
     * @return  bool
     */
    public function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS) {
        if ($order_id <= 0) {
            $sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') .
            "cart WHERE session_id = '" . SESS_ID . "' AND is_real = 1 " .
            "AND rec_type = '$flow_type'";
        } else {
            $sql = "SELECT COUNT(*) as count FROM " . C('DB_PREFIX') .
            "order_goods WHERE order_id = '$order_id' AND is_real = 1";
        }
        $sql.=' limit 1';
        $Model=new Model();
        $res = $Model->query($sql);
        return $res[0]['count'] > 0;
    }
    
   
    /*
     *  
     * 获取收货地址总数
     * */
    public function get_addresscount($where){
        return $this->where($where)->count();
    }
    /**
     *根据订单ID查询配送信息
     */
    public function check_serve_by_order_id($order_id){

        $order_info = M("order_info")->
        field('province,city,district,address,longitude,latitude,sign_building')
            ->where('order_id = '.$order_id)->find();

        $province = M('region')->where('region_id ='.$order_info['province'])->getField('region_name');
        $city = M('region')->where('region_id ='.$order_info['city'])->getField('region_name');
        $district = M('region')->where('region_id ='.$order_info['district'])->getField('region_name');
        $all_address = $province.$city.$district.$order_info['address'];
        $address['all_address'] = str_replace(' ','',$all_address);
        $address['lit_address'] = $order_info['address'];

        $address['longitude'] = $order_info['longitude'];
        $address['latitude'] = $order_info['latitude'];
        $address['sign_building'] = $order_info['sign_building'];

        //dump($address);
        $gps = M("louxiaoer_landmark")->where(array("name"=>$address['sign_building'],"is_check"=>1,"lat"=>array("gt",0)))->field("lat,lng")->find();
        if($gps['lat']>0){
            $address_gps['longitude'] = $gps['lat'];
            $address_gps['latitude'] = $gps['lng'];
            //dump($address_gps);
        }else{
            $address_gps['longitude'] = $address['latitude'];
            $address_gps['latitude'] = $address['longitude'];
        }


        //dump($address_gps);
        //exit();
        $distribution_data = $this->get_distribution_by_gps($address_gps['longitude'],$address_gps['latitude']);
        //dump($distribution_data);
        if($distribution_data){
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =1;
        }else{
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =0;
        }
        return $distribution_data;
    }
    /**
     *根据指定地址查询配送信息
     * $address 地址
     * $sign_building 地标
     */
    public function check_serve_by_address($address,$sign_building){
        $gps = M("landmark_repair")->where(array("name"=>$sign_building))->field("lat,lng")->find();
        if($gps['lat']>0){
            $address_gps['longitude'] = $gps['lat'];
            $address_gps['latitude'] = $gps['lng'];
            //dump($address_gps);
        }else{
            $address_gps = address_to_gps_amap($address,$address['city']);
        }

        $distribution_data = $this->get_distribution_by_gps($address_gps['longitude'],$address_gps['latitude']);

        //dump($distribution_data);
        if($distribution_data){
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =1;
        }else{
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =0;
        }
        if($_POST['is_app']==1&&$_POST['version']<48){


            if($distribution_data['is_day']==0){
                $distribution_data['is_day']=1;
            }elseif($distribution_data['is_day']==1){
                $distribution_data['is_day']=0;
            }

        }
        return $distribution_data;
    }
    /**
     *根据用户地址ID查询配送信息
     */
    public function check_serve_by_address_id($address_id){
        $address = $this->get_address_by_id($address_id);

        $gps = M("landmark_repair")->where(array("name"=>$address['sign_building'],"district_id"=>$address['district_id']))->field("lat,lng")->find();

        if($gps['lat']>0){
            $address_gps['longitude'] = $gps['lat'];
            $address_gps['latitude'] = $gps['lng'];
        }else{
            if($address['is_ok']==1&&!empty($address['longitude'])&&!empty($address['latitude'])){
                //已确认坐标
                $address_gps = $address;
            }else{
                $address_gps = address_to_gps_amap($address['address_building'],$address['city']);
                //dump($address_gps);
                $data['longitude'] = $address_gps['longitude'];
                $data['latitude'] = $address_gps['latitude'];
                $data['is_ok'] = 1;
                M("user_address")->where('address_id ='.$address_id)->save($data);
            }
        }
        //dump($address_gps);
        $distribution_data = $this->get_distribution_by_gps($address_gps['longitude'],$address_gps['latitude']);
        //匹配中
        if($distribution_data){
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =1;
        }else{
            $distribution_data['all_address'] = $address['all_address'];
            $distribution_data['lit_address'] = $address['lit_address'];
            $distribution_data['return'] =0;
        }
        if($_POST['is_app']==1&&$_POST['version']<61){
            if($distribution_data['is_day']==0){
                $distribution_data['is_day']=1;
            }elseif($distribution_data['is_day']==1){
                $distribution_data['is_day']=0;
            }

        }
        return $distribution_data;
    }
    
    
    /**
     * 根据ID查询详细地址
     * Author:何锐 <poptser@foxmail.com>
     * @param $address_id
     * @return bool|string
     */
    public function get_address_by_id($address_id){
		return D('Users')->get_address_by_id($address_id);
    }
    
    
    
    /**
     * 获取用户默认地址的GPS坐标值
     * Author:何锐 <poptser@foxmail.com>
     * @param $uid
     * @return bool|void
     */
    public function get_user_default_address_gps($uid){
        $where['user_id'] = $uid;
        $where['default'] = 1;
        $user_address_id = M("user_address")->where($where)->getField('address_id');
        if ($user_address_id){
            $data = $this->get_address_by_id($user_address_id);
            $data['gps'] = address_to_gps_amap($data['building_address']);
            return $data;
        }else{
            return false;
        }
    }
    
    /**
     * 根据经纬度获取区域优惠信息
     * @param $longitude
     * @param $latitude
     */
    public function get_distribution_by_gps($longitude, $latitude){
		return D('Users')->get_distribution_by_gps($longitude,$latitude);
    }
    
    
    /**
     * 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    public function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];
    
            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
                return true;
    
            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px)
                    return true;
                if ($x > $px)
                    $flag = !$flag;
            }
        }
        return $flag;
    }

    /**
     * 根据名字转ID
     * @param $name
     * @param $level
     * @return mixed
     */
    public function get_address_id($name, $level){
        $name = str_replace(array('省','市','区','县','自治区','自治州','自治镇','自治县','特别行政区'),'',$name);
        return M('region')->where("region_type = ".$level ." and region_name like '%".$name."%'")->getField("region_id");
    }
    
    /**
     * 取得收货人信息
     * @param   int     $user_id    用户编号
     * @return  array
     */
    function get_consignee($user_id,$address_id = '') {
        /* 如果不存在，则取得用户的默认收货人信息 */
        $arr = array();
        if ($user_id > 0) {
            /* 取默认地址 */
        	if($address_id){
        		$where=array(
        				'user_id'=>$user_id,
        				'address_id'=>$address_id
        		);
        	}else{
        		$where=array(
        				'user_id'=>$user_id,
        				'default'=>1
        		);
        	}
            
            $arr=$this->where($where)->find();

            $gps = M("landmark_repair")->where(array("name"=>$arr['sign_building'],"district_id"=>$arr['district']))->field("lat,lng")->find();

            if($gps['lat']>0){
                    $arr['latitude'] =$gps['lat'];
                    $arr['longitude'] =$gps['lng'];
            }else{
                $user_address = M("user_address")->where(array("address_id"=>$address_id,"is_ok"=>1))->find();

                if(!empty($user_address['longitude'])&&!empty($user_address['latitude'])){
                    if($user_address['longitude']>$user_address['latitude']){
                        $arr['latitude'] =$user_address['longitude'];
                        $arr['longitude'] =$user_address['latitude'];
                    }else{
                        $arr['longitude'] =$user_address['longitude'];
                        $arr['latitude'] =$user_address['latitude'];
                    }
                }
            }
        }

        return $arr;
    
    }
    
}